package com.nuaa.yupicturebackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuaa.yupicturebackend.mapper.CommentMapper;
import com.nuaa.yupicturebackend.mapper.UserMapper;
import com.nuaa.yupicturebackend.model.dto.comment.CommentAddRequest;
import com.nuaa.yupicturebackend.model.entity.Comment;
import com.nuaa.yupicturebackend.model.entity.User;
import com.nuaa.yupicturebackend.model.vo.CommentVO;
import com.nuaa.yupicturebackend.service.CommentService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: ortonzhu
 * @data 2025年03月20日 12:37
 * @Description
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {
	@Resource
	private UserMapper userMapper;

	@Resource
	private CommentMapper commentMapper;

	@Override
	public List<CommentVO> getRootCommentsByImage(Long pictureId) {
		List<Comment> allComments = query().eq("pictureId", pictureId).list();
		Map<Long, CommentVO> commentVOMap = new HashMap<>();
		// 初始化 CommentVO 对象
		for (Comment comment : allComments) {
			CommentVO commentVO = new CommentVO();
			BeanUtils.copyProperties(comment, commentVO);
			User user = userMapper.selectById(comment.getUserId());
			commentVO.setUserName(user.getUserName());
			commentVO.setUserAvatar(user.getUserAvatar());
			commentVOMap.put(comment.getId(), commentVO);
		}

		// 构建树结构
		List<CommentVO> rootCommentVOs = new ArrayList<>();
		for (CommentVO commentVO : commentVOMap.values()) {
			if (commentVO.getParentId() == -1) {
				rootCommentVOs.add(commentVO);
			} else {
				CommentVO parentCommentVO = commentVOMap.get(commentVO.getParentId());
				if (parentCommentVO != null) {
					if (parentCommentVO.getChildren() == null) {
						parentCommentVO.setChildren(new ArrayList<>());
					}
					parentCommentVO.getChildren().add(commentVO);
				}
			}
		}

		return rootCommentVOs;
	}

	@Override
	public List<Comment> searchComments(String keyword) {
		QueryWrapper<Comment> wrapper = new QueryWrapper<>();
		wrapper.like("content", keyword)
				.or()
				.like("userId", keyword);
		return list(wrapper);
	}

	@Override
	public Boolean saveComment(CommentAddRequest commentAddRequest) {
		Comment comment = new Comment();
		BeanUtils.copyProperties(commentAddRequest, comment);
		return save(comment);
	}

	@Override
	public Boolean deleteComment(Integer commentId) {
		int res = commentMapper.deleteById(commentId);
		// 删除该评论的所有子评论
		commentMapper.delete(new QueryWrapper<Comment>().eq("parentId", commentId));
		return res > 0;
	}
}
